<template>
	<view class="main cityList-main">
		<NavigationBar title="选择城市" />
		<scroll-view class="scroll-wrap" @scroll="scroll" :scroll-top="scrollTopValue" scroll-y="true">
			<view class="list-item" v-for="item in cityList">
				<view class="letter-row" :id="item.letter">{{item.letter}}</view>
				<view class="city-row b-b" v-for="cityItem in item.data" @click="selectCityAction(cityItem)">{{cityItem.name}}</view>
			</view>
			<view class="key-list">
				<view 
				v-for="(item,index) in cityList" 
				:class="['key-item',{'active':letterStr==item.letter}]" 
				@click="clickKey(item.scrollTopValue)"
				>{{item.letter}}</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex'
	export default {
		data() {
			return {
				cityList: [],
				scrollTopValue: 0,
				letterStr: 'A',
				statusBarHeight: 0
			};
		},
		onLoad() {
			this.getCityAction()
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
		},
		methods: {
			async getCityAction() {
				const _this = this
				let params = {}
				let res = await _this.axios.post(_this.api.getCity)
				if (res.code == 200) {
					let dataArr = res.data
					let resArr = []
					for (var i = 0; i < 25; i++) {
						let zimu = String.fromCharCode((65 + i))
						let newArr = dataArr.filter((item) => {
							if (item.spinyin == zimu) {
								return item
							}
						})
						if (newArr.length > 0) {
							let obj = {
								letter: zimu,
								data: newArr
							}
							resArr.push(obj)
						}
					}
					// console.log(resArr)
					_this.cityList = resArr

					_this.$nextTick(function() {
						const query = uni.createSelectorQuery().in(this);
						resArr.map((item) => {
							query.select(`#${item.letter}`).boundingClientRect(data => {
								item.scrollTopValue = parseInt(data.top) - 44 - _this.statusBarHeight
							}).exec();
						})
					})
				}
			},
			scroll(e) {
				let _this = this
				let scrollTop = e.detail.scrollTop
				
				let letterStr = this.letterStr
				this.cityList.forEach((item, index) => {
					if (scrollTop > (item.scrollTopValue - 2)) {
						letterStr = item.letter
					}
				})
				if (this.letterStr != letterStr) {
					this.letterStr = letterStr
					this.scrollTopValue = scrollTop
				}
			},
			clickKey(value) {
				console.log(value)
				this.scrollTopValue = value
			},
			selectCityAction(city) {
				this.setCityInfo(city)
				this.$util.goBack()
			},
			...mapMutations(['setCityInfo'])
		}
	}
</script>

<style lang="scss">
	@import "./cityList.scss";
</style>
